package store.lunangangster.nodeflow.parser.el.operator;

import static store.lunangangster.nodeflow.enums.FlowType.FLOW_IF;

import cn.hutool.core.collection.CollUtil;
import com.ql.util.express.Operator;
import store.lunangangster.nodeflow.builder.FlowBuilder;
import store.lunangangster.nodeflow.core.component.IfComponent;
import store.lunangangster.nodeflow.exception.RuleSourceParseException;
import store.lunangangster.nodeflow.parser.el.OperatorHelper;
import store.lunangangster.nodeflow.rt.element.Executable;
import store.lunangangster.nodeflow.rt.element.Node;
import store.lunangangster.nodeflow.rt.element.flow.IfFlow;

/**
 * If表达式所关联的操作符
 *
 * @author cwk
 * @version 1.0
 */
public class IfOperator extends Operator {

  @Override
  public Object executeInner(Object[] list) throws RuleSourceParseException {
    OperatorHelper.checkArguments(list);

    if (list.length < 1 || list.length > 3) {
      throw new RuleSourceParseException("Incompatible executable for IfFlow: should be like IF(ifNode) or IF(ifNode, trueFlow) or IF(ifNode, falseFlow)");
    }
    Node ifNode = (Node) list[0];
    if (!ifNode.isComponent(IfComponent.class)) {
      throw new RuleSourceParseException("Incompatible executable for IfFlow: should be like IF(ifNode) or IF(ifNode, trueFlow) or IF(ifNode, falseFlow)");
    }
    IfFlow ifFlow = (IfFlow) FlowBuilder.buildELFLow(FLOW_IF, CollUtil.toList(ifNode));
    if (list.length >= 2) {
      ifFlow.setTrueBranch((Executable) list[1]);
    }
    if (list.length == 3) {
      ifFlow.setFalseBranch((Executable) list[2]);
      ifFlow.setIsElse(true);
    }
    return ifFlow;
  }
}
